//
//  RtcEngine.swift
//  onemeetingmac
//
//  Created by 张衡 on 2020/5/27.
//  Copyright © 2020 onemeeting. All rights reserved.
//

import Foundation



class RtcEngine: NSObject {
    
    static let shared = RtcEngine()
    
    class func saveWebHostData(mode:MeetingMode) {
        UserInfoManager.shared.yhwownidKey = mode.wifiId
        UserInfoManager.shared.yhwownid    = mode.ownid
    }
    
    class func saveWebDataConfig(mode:ScriptMode) {
        UserInfoManager.shared.scene = mode.islive ? 1:0
        UserInfoManager.shared.ownid = mode.ownid
        Td.sh().lc.nickName = mode.name ?? ""
        Td.sh().isJoin = !mode.ishost
        Td.sh().params.roomId = mode.roomid
    }
    
    /// 设置默认数据
    /// - Parameter model: 数据mode
    class func saveData(mode:MeetingMode) {
        UserInfoManager.shared.ownid    = mode.ownid
        UserInfoManager.shared.ownidKey = mode.wifiId
        Td.sh().live.liveurl            = mode.liveurl
        Td.sh().live.rtmpurl            = mode.rtmpurl
        Td.sh().cloud.hasLive           = mode.is_live==0 ? false:true
        Td.sh().cloud.isVip             = mode.vip=="0" ? false:true
        Td.sh().cloud.days              = mode.days ?? 0
        if let usersig = mode.usersig {
            Td.sh().params.userSig      = usersig
        }
    }
    
    class func saveJoinCloud(mode:SCloudMode) {
        Td.sh().cloud.disSd       = mode.is_share.bool
        Td.sh().cloud.disBararage = mode.is_silent.bool
        Td.sh().cloud.disLink     = mode.is_mike.bool
        Td.sh().cloud.isALLMute   = mode.is_speak == 1 ? false:true
        Td.sh().cloud.focusId     = mode.focusid
    }
    
    
    class func saveHostMode(mode:HostMode) {
        Td.sh().cloud.hostId            = Td.sh().params.roomId ?? "000000"
        Td.sh().cloud.meetingCount      = Int(truncating: mode.count ?? 10)
        Td.sh().cloud.meetingTime       = Float(truncating: mode.time ?? 3600)
        Td.sh().cloud.passwordCloud     = mode.password ?? ""
        if let scene = mode.scene {
            UserInfoManager.shared.scene = scene
        }
        
        
    }
    
    class func saveSceneData(isjoin:Bool) {
        Td.sh().isJoin = isjoin
        if Td.sh().scene == .live {
            let role = isjoin ? TRTCRoleType.audience:TRTCRoleType.anchor
            Td.sh().params.role = role
        }
    }
}

extension RtcEngine {
    /**
    获取会议号
    */
    class func responseMeetingID(success:ResultSuccess_obj? = nil){
        let ownidKey = UserInfoManager.shared.ownidKey ?? ""
        NetEngine.respose_getMeetingNum(ownidKey: ownidKey, success: { (result) in
            //let mode = SMeetingMode.deserialize(from: result)
            //RtcEngine.saveWifiData(mode: mode!)
            if success != nil {
                success!(result!)
            }
        }, fail: nil)
    }
    
    
    /**
    获取会议信息
    */
    class func responseHostData(success:ResultSuccess? = nil) {
        let ownidKey = UserInfoManager.shared.ownidKey ?? ""
        NetEngine.getHostInfo(wifiId: ownidKey) { (mode) in
            RtcEngine.saveData(mode: mode!)
            if success != nil {
                success!(mode?.toJSON() ?? [:])
            }
        }
    }
    
    /**
    上一场会议
    */
    class func responseLastHostMeeting(roomid:String,success:ResultSuccess?=nil)  {
        NetEngine.respose_MeetStutas(roomId: roomid, success: { (result) in
            let mode = SCloudMode.deserialize(from: result)
            RtcEngine.saveJoinCloud(mode: mode!)
            if success != nil {
                success!(result)
            }
        }) { (code,error) in
            
        }
    }
    
    
    /**
    召开主持会议
    */
    class func responseHost(scene:String,ownid:String,success:ResultSuccess?=nil,last:ResultLast?=nil) {
        Td.sh().params.roomId = ownid
        NetEngine.getHostMeetingStatus(roomId: ownid, scene: scene, success: { (kResult) in
            let mode = HostMode.deserialize(from: kResult)
            RtcEngine.saveHostMode(mode: mode!)
            RtcEngine.saveSceneData(isjoin: false)
            if success != nil {
                success!(kResult)
            }
        }) { (sResult) in
            let mode = HostMode.deserialize(from: sResult)
            RtcEngine.saveHostMode(mode: mode!)
            RtcEngine.saveSceneData(isjoin: false)
            if last != nil {
                last!(sResult)
            }
        }
    }
    
    
    /**
    加入会议
    */
    class func responseJoin(roomid: String, userid: String,success:ResultSuccess?=nil,fail:ResultNo?=nil,passwrodResult:ResultSuccess?=nil) {
        Td.sh().params.roomId = roomid
        NetEngine.getJoinMeetingStatus(roomId: roomid, userid: userid) { (sResult) in
            self.JoinStatus(roomid: roomid, result: sResult, success: success)
        } fail: { (code, message) in
            show_msg(message)
            if fail != nil {
                fail!()
            }
        } passwrodResult: { (result) in
            self.JoinStatus(roomid: roomid, result: result, success: passwrodResult)
        }
    }
    
    class func JoinStatus(roomid:String, result:[String:Any]?,success:ResultSuccess?=nil) {
        let mode = HostMode.deserialize(from: result)
        RtcEngine.saveHostMode(mode: mode!)
        RtcEngine.saveSceneData(isjoin: true)
        NetEngine.respose_MeetStutas(roomId: roomid, success: { (lResult) in
            let mode = SCloudMode.deserialize(from: lResult)
            RtcEngine.saveJoinCloud(mode: mode!)
            if success != nil {
                success!(lResult)
            }
        }) { (code,message) in
            show_msg(message)
        }
    }

    /**
    获取推流信息
    */
    class func getRtmp(type:OnePushType,success:ResultSuccess? = nil) {
        guard let ownid = Td.sh().params.roomId else {
            return
        }
        NetEngine.getMeetingLive(ownid: ownid,roomid: ownid, push: type) { (result) in
            if success != nil {
                success!(result)
            }
        }
    }
    
}

//MARK:- 壹会网专业用
extension RtcEngine {
    
    class func responseUsersig(userId:String,roomid:String,success:os_block_t? = nil) {
        NetEngine.getUserSig(userId: userId, roomId: roomid) { (result) in
            if let dict = result {
                let usersig = dict["usersig"] as? String
                Td.sh().params.userSig = usersig
            }
            if success != nil {
                success!()
            }
        }
    }
    
    //获取会议号
    class func responseOneMeetingID(success:ResultSuccess_obj? = nil){
        let ownidKey = UserInfoManager.shared.yhwownidKey ?? ""
        NetEngine.respose_getOneMeetingNum(ownidKey: ownidKey, success: { (result) in
            let mode = MeetingMode.deserialize(from: result)
            RtcEngine.saveWebHostData(mode: mode!)
            if success != nil {
                success!(result!)
            }
        }, fail: nil)
    }
}


extension String {
    func clear_ownid() -> String {
        if self[0] == "c" {
            return self.substring(fromIndex: 1)
        }
        return self
    }
}
